<template>
  <div>
    <el-form
      :model="commodityForm"
      :rules="commodityFormRules"
      ref="commodityFormRef"
      label-width="150px"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="commodityForm.name"
          placeholder="请输入，将用于客户端商品名称展示（建议20字以内）"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-select
          v-model="commodityForm.type"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option key="1" label="单品" value="1"> </el-option>
          <el-option key="2" label="组合商品" value="2"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品类别" prop="class">
        <el-select
          v-model="commodityForm.class"
          placeholder="请选择"
          filterable
          clearable
        >
          <el-option
            v-for="item in selectData.goods_class"
            :key="item.id"
            :label="item.name"
            :value="
              typeof commodityForm.class == 'string' ? item.id + '' : item.id
            "
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属产品分类" prop="product_type_codes">
        <el-select
          v-model="commodityForm.product_type_codes"
          placeholder="请选择分类"
          filterable
          clearable
          :multiple="commodityForm.type == 2"
          v-if="update"
        >
          <!-- @change="sendTypeCodes" -->
          <el-option
            v-for="item in selectData.product_type"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品标签" prop="tags">
        <el-input
          v-model="commodityForm.tags"
          placeholder="请输入商品标签，多个用逗号隔开（用于客户端商品特性描述）"
        ></el-input>
      </el-form-item>
      <el-form-item label="商品banner主图" prop="cover_url" required>
        <el-upload
          :action="ossUrl"
          :headers="ossHeader"
          list-type="picture-card"
          :auto-upload="true"
          :limit="1"
          v-model="commodityForm.cover_url"
          :on-success="uploadSuccessMain"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemoveMain"
          :data="{ system: 'chongtai', module: '商品图片' }"
          :class="{ uoloadSty: showBtnImgMain, disUoloadSty: noneBtnImgMain }"
          :on-change="imgChangeMain"
          :file-list="commodityForm.coverUrlList"
          :before-upload="beforeUpload"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div class="el-upload__tip" slot="tip">
            <ul style="margin-left: -25px; line-height: 20px; color: grey">
              <li>请上传jpg或png格式的图片，大小不超过2M</li>
              <li>上传的图片尺寸为750*750px，或长宽等比例的图片</li>
            </ul>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品banner辅图" prop="carousel_url">
        <el-upload
          :action="ossUrl"
          :headers="ossHeader"
          list-type="picture-card"
          :auto-upload="true"
          :limit="imgLimit"
          :on-exceed="handleExceed"
          v-model="commodityForm.carousel_url"
          :on-success="uploadSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :data="{ system: 'chongtai', module: '商品图片' }"
          :class="{ uoloadSty: showBtnImg, disUoloadSty: noneBtnImg }"
          :on-change="imgChange"
          :file-list="commodityForm.carouselUrlList"
          :before-upload="beforeUpload"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div class="el-upload__tip" slot="tip">
            <ul style="margin-left: -25px; line-height: 20px; color: grey">
              <li>请上传jpg或png格式的图片，大小不超过2M，5张以内</li>
              <li>上传的图片尺寸为750*750px，或长宽等比例的图片</li>
            </ul>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品详情图" prop="details_url" required>
        <el-upload
          :action="ossUrl"
          :headers="ossHeader"
          list-type="picture-card"
          :auto-upload="true"
          :limit="imgLimitDetail"
          :on-exceed="handleExceedDetail"
          v-model="commodityForm.details_url"
          :on-success="uploadSuccessDetail"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemoveDetail"
          :data="{ system: 'chongtai', module: '商品图片' }"
          :class="{
            uoloadSty: showBtnImgDetail,
            disUoloadSty: noneBtnImgDetail
          }"
          :on-change="imgChangeDetail"
          :file-list="commodityForm.detailsUrlList"
          :before-upload="beforeUpload"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div class="el-upload__tip" slot="tip">
            <ul style="margin-left: -25px; line-height: 20px; color: grey">
              <li>请上传jpg或png格式的图片，大小不超过2M，20张以内</li>
              <li>上传的图片的宽度为750px</li>
            </ul>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品icon图标" prop="icon_url" required>
        <el-upload
          :action="ossUrl"
          :headers="ossHeader"
          list-type="picture-card"
          :auto-upload="true"
          :limit="1"
          v-model="commodityForm.icon_url"
          :on-success="uploadSuccessIcon"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemoveIcon"
          :data="{ system: 'chongtai', module: '商品图片' }"
          :class="{ uoloadSty: showBtnImgIcon, disUoloadSty: noneBtnImgIcon }"
          :on-change="imgChangeIcon"
          :file-list="commodityForm.iconUrlList"
          :before-upload="beforeUpload"
        >
          <i slot="default" class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          v-model="commodityForm.remark"
          show-word-limit
          maxlength="500"
        ></el-input>
      </el-form-item>
    </el-form>

    <!-- 放大图片弹窗 -->
    <el-dialog :visible.sync="dialogVisible" width="45%" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    commodityData: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    var imageValidator = (rule, value, callback) => {
      if (this.commodityForm.coverUrlList.length === 0) {
        callback(new Error('请上传商品banner主图'))
      }
      callback()
    }
    var imageValidatorMulti = (rule, value, callback) => {
      // console.log(rule)
      // console.log(this.commodityForm.detailsUrlList)
      if (this.commodityForm.detailsUrlList.length == 0) {
        callback(new Error('请上传商品详情图'))
      }
      callback()
    }
    var imageValidatorIcon = (rule, value, callback) => {
      if (
        this.commodityForm[rule.field] === undefined ||
        this.commodityForm[rule.field] === ''
      ) {
        callback(new Error('请上传商品icon图标'))
      }
      callback()
    }
    return {
      commodityForm: {
        id: '',
        name: '',
        type: '',
        class: '',
        product_type_codes: '',
        tags: '',
        cover_url: '',
        carousel_url: [],
        remark: '',
        details_url: [],
        icon_url: ''
      },
      commodityFormRules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        class: [{ required: true, message: '请选择', trigger: 'change' }],
        product_type_codes: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        // tags: [{ required: true, message: '请输入', trigger: 'blur' }],
        cover_url: [{ validator: imageValidator }],
        details_url: [{ validator: imageValidatorMulti }],
        icon_url: [{ validator: imageValidatorIcon }]
      },

      //   图片信息
      dialogImageUrl: '',
      dialogVisible: false,
      ossUrl: this.GLOBAL.ossUrl,
      ossHeader: this.GLOBAL.ossHeader,

      // 商品banner主图
      showBtnImgMain: true,
      noneBtnImgMain: false,
      // 商品banner辅图
      imgLimit: 5,
      showBtnImg: true,
      noneBtnImg: false,
      // 商品详情图信息
      imgLimitDetail: 20,
      showBtnImgDetail: true,
      noneBtnImgDetail: false,
      // 商品icon图标信息
      showBtnImgIcon: true,
      noneBtnImgIcon: false,

      selectData: [],
      update: true // 控制多选变化时不渲染组件，计算完再渲染组件
    }
  },
  created() {
    this.getSelectData()
    this.initData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'product_type,goods_class',
        level: 2
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData = res.data
    },
    initData() {
      this.commodityForm = JSON.parse(JSON.stringify(this.commodityData))
      this.noneBtnImgMain = this.commodityForm.coverUrlList.length === 1
      this.noneBtnImg =
        this.commodityForm.carouselUrlList.length >= this.imgLimit
      this.noneBtnImgDetail =
        this.commodityForm.detailsUrlList.length >= this.imgLimitDetail
      this.noneBtnImgIcon = this.commodityForm.iconUrlList.length === 1
    },
    //   删除图片
    handleRemove(file, fileList) {
      var a = this.commodityForm.carouselUrlList.findIndex(
        (item) => item.uid === file.uid
      )
      if (a !== -1) {
        this.commodityForm.carouselUrlList.splice(a, 1)
      }
      this.noneBtnImg = fileList.length >= this.imgLimit
    },
    // 超出限制时的行为
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ` +
          this.imgLimit +
          ` 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
      )
    },
    uploadSuccess(response, file, fileList) {
      if (Number.parseInt(response.code) === 10001) {
        file.url = response.data.url
        this.commodityForm.carouselUrlList.push(file)
      } else {
        this.$message.error(response.message)
        var a = fileList.findIndex((item) => item.uid === file.uid)
        if (a !== -1) {
          fileList.splice(a, 1)
        }
      }
    },
    imgChange(file, fileList) {
      this.noneBtnImg = fileList.length >= this.imgLimit
    },
    // -------------图片上传公共方法------------
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      } else if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 放大图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // -----------------------------------------
    // -------------商品banner主图操作-----------
    uploadSuccessMain(response, file, fileList) {
      if (Number.parseInt(response.code) === 10001) {
        this.commodityForm.coverUrlList.push(file)
        this.commodityForm.cover_url = response.data.url
      } else {
        this.$message.error(response.message)
        var a = fileList.findIndex((item) => item.uid === file.uid)
        if (a !== -1) {
          fileList.splice(a, 1)
        }
      }
    },
    //   删除图片
    handleRemoveMain(file, fileList) {
      this.noneBtnImgMain = fileList.length === 1
      for (var i = 0; i < this.commodityForm.coverUrlList.length; i++) {
        if (this.commodityForm.coverUrlList[i].uid == file.uid) {
          this.commodityForm.coverUrlList.splice(i, 1)
        }
      }
      this.commodityForm.cover_url = ''
    },
    imgChangeMain(file, fileList) {
      this.noneBtnImgMain = fileList.length === 1
    },
    // -----------------------------------
    validateForm() {
      let flag = false
      this.$refs.commodityFormRef.validate(async (valid) => {
        if (valid) {
          flag = true
          // 处理数据
          const result = this.handleFormData()
          this.$emit('showCommodityBaseInfo', result)
        } else {
          flag = false
        }
      })
      return flag
    },
    handleFormData() {
      const data = JSON.parse(JSON.stringify(this.commodityForm))
      var carousel_url = []
      for (let i = 0; i < data.carouselUrlList.length; i++) {
        carousel_url.push(data.carouselUrlList[i].url)
      }
      data.carousel_url = carousel_url.join(',')

      var details_url = []
      for (let i = 0; i < data.detailsUrlList.length; i++) {
        details_url.push(data.detailsUrlList[i].url)
      }
      data.details_url = details_url.join(',')

      if (data.type == 2) {
        data.product_type_codes = data.product_type_codes.join(',')
      }
      return data
    },
    // sendTypeCodes(val) {
    //   var temp = val
    //   if (this.commodityForm.type == 2) {
    //     temp = val.join(',')
    //   }
    //   this.$emit('showCommodityBaseInfo', {
    //     type: this.commodityForm.type,
    //     product_type_codes: temp
    //   })
    // }
    // -------------商品详情图操作-----------
    // 超出限制时的行为
    handleExceedDetail(files, fileList) {
      this.$message.warning(
        `当前限制选择 ` +
          this.imgLimitDetail +
          ` 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
      )
    },
    uploadSuccessDetail(response, file, fileList) {
      if (Number.parseInt(response.code) === 10001) {
        file.url = response.data.url
        this.commodityForm.detailsUrlList.push(file)
        this.commodityForm.details_url = response.data.url
      } else {
        this.$message.error(response.message)
        var a = fileList.findIndex((item) => item.uid === file.uid)
        if (a !== -1) {
          fileList.splice(a, 1)
        }
      }
    },
    //   删除图片
    handleRemoveDetail(file, fileList) {
      var a = this.commodityForm.detailsUrlList.findIndex(
        (item) => item.uid === file.uid
      )
      if (a !== -1) {
        this.commodityForm.detailsUrlList.splice(a, 1)
      }
      this.noneBtnImgDetail = fileList.length >= this.imgLimitDetail
      this.commodityForm.details_url =
        this.commodityForm.detailsUrlList.join(',')
    },
    imgChangeDetail(file, fileList) {
      this.noneBtnImgDetail = fileList.length >= this.imgLimitDetail
    },
    // -------------------------------
    // -------------商品icon图标的操作------------
    uploadSuccessIcon(response, file, fileList) {
      if (Number.parseInt(response.code) === 10001) {
        this.commodityForm.iconUrlList.push(file)
        this.commodityForm.icon_url = response.data.url
      } else {
        this.$message.error(response.message)
        var a = fileList.findIndex((item) => item.uid === file.uid)
        if (a !== -1) {
          fileList.splice(a, 1)
        }
      }
    },
    //   删除图片
    handleRemoveIcon(file, fileList) {
      this.noneBtnImgIcon = fileList.length === 1
      for (var i = 0; i < this.commodityForm.iconUrlList.length; i++) {
        if (this.commodityForm.iconUrlList[i].uid == file.uid) {
          this.commodityForm.iconUrlList.splice(i, 1)
        }
      }
      this.commodityForm.icon_url = ''
    },
    imgChangeIcon(file, fileList) {
      this.noneBtnImgIcon = fileList.length === 1
    }
    // ------------------------------------------
  },
  watch: {
    'commodityForm.type'() {
      this.update = false
      setTimeout(() => {
        this.update = true
      })
    },
    commodityData() {
      this.commodityForm = JSON.parse(JSON.stringify(this.commodityData))
      console.log(this.commodityForm)
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 80%;
  margin-left: 15px;
  .el-select {
    width: 100%;
  }
}
/deep/ .uoloadSty .el-upload--picture-card {
  // width: 230px;
  display: true;
}
/deep/ .disUoloadSty .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
/deep/ .uoloadSty .el-upload-list__item {
  width: 148px;
}
</style>
